import { defineComponent } from 'vue'
import {
  ElForm as Form,
  ElInput as Input,
  ElSelect as Select,
  ElOption as Option,
  ElFormItem as FormItem,
  ElRow as Row,
  ElCol as Col,
  ElButton as Button,
  ElSpace as Space,
  ElDatePicker as DatePicker,
} from 'element-plus'
import { useI18n } from 'vue-i18n'
import { isJSON } from '@/utils'
const searchItems = {
  input({ item, props, model }) {
    return <Input {...props} v-model={this.formInline[model]} />
  },
  select({ item, props, model }) {
    const { options, ...other } = props
    const $props = { ...other }
    return (
      <Select {...$props} v-model={this.formInline[model]}>
        {options.map((item, index) => (
          <Option key={index} label={item.label} value={item.value} />
        ))}
      </Select>
    )
  },
  date({ item, props, model }) {
    return (
      <DatePicker
        style={{
          width: 'auto',
        }}
        v-model={this.formInline[model]}
        {...props}
      />
    )
  },
  datetime({ item, props, model }) {
    return (
      <DatePicker
        style={{
          width: 'auto',
        }}
        v-model={this.formInline[model]}
        {...props}
      />
    )
  },
}
export default defineComponent({
  name: 'SSearch',
  props: {
    searchList: {
      type: [Array],
      default: function () {
        return []
      },
    },
  },
  watch: {
    disabledSearch(value) {
      if (value) {
        this.onClear()
      }
    },
    searchParams() {
      this.debounceFetch()
    },
  },
  computed: {
    searchListC() {
      const { t } = useI18n()
      const searchList = this.searchList
      const index = searchList.findIndex((item) => item.type === 'langs')
      let path
      if (index >= 0) {
        path = (searchList.splice(index, 1)?.[0] ?? {})?.path
      }
      return searchList.map((item) => {
        item.size = item?.size ?? 'default'
        if (item.model && item.placeholder && path) {
          item.placeholder = t(`${path}.${item.model + 'Tips'}`)
          const { options: searchOptions, type } = item
          const options = isJSON(t(`${path}.${item.model + 'Options'}`))
            ? JSON.parse(t(`${path}.${item.model + 'Options'}`))
            : false

          if (searchOptions && options) {
            searchOptions.forEach((subItem, index) => {
              if (['radio', 'select'].includes(type)) {
                subItem.label = options[index]
              }
              if (['checkbox'].includes(type)) {
                searchOptions[index] = options[index]
              }
            })
          }
        }
        return item
      })
    },
  },
  methods: {
    onSearch() {
      this.loading = true
      this.searchParams = { ...this.formInline }
    },
    onClear() {
      Object.keys(this.formInline).forEach(
        (item) => (this.formInline[item] = undefined)
      )
      this.searchParams = { ...this.formInline }
    },
    // 防抖请求数据
    debounceFetch() {
      this.debounceFetch.timer && clearTimeout(this.debounceFetch.timer)

      this.debounceFetch.timer = setTimeout(() => {
        this.loading = false
        this.$emit('searchRefreshTable', this.searchParams)
      }, 250)
    },
    renderExtra(extra) {
      if (!extra) {
        return
      }
      return (
        <FormItem class="mr-0">
          <Space size={0}>{extra('新增')}</Space>
        </FormItem>
      )
    },
    renderSearchList() {
      if (!this.searchList.length) {
        return
      }
      return [this.renderSearchItems(), this.renderSearchBtn()]
    },
    renderSearchItems() {
      const { searchListC: searchList } = this
      return searchList.map((item) => {
        const { model, type, ...other } = item
        const props = {
          ...other,
        }
        const SEARCH_DOM = this.searchItems[type].call(this, {
          item,
          props,
          model,
        })
        return <FormItem class="mr-16">{SEARCH_DOM}</FormItem>
      })
    },
    renderSearchBtn() {
      const { t } = useI18n()
      const { loading } = this
      const SEARCH_BTN_DOM = (
        <Button
          loading={loading}
          icon="search"
          type="primary"
          onClick={this.onSearch}
        >
          {t('button.search')}
        </Button>
      )
      const CLEAR_BTN_DOM = (
        <Button icon="delete" onClick={this.onClear}>
          {t('button.clear')}
        </Button>
      )

      return (
        <FormItem class="mr-0">
          <Space size={10}>
            {SEARCH_BTN_DOM}
            {CLEAR_BTN_DOM}
          </Space>
        </FormItem>
      )
    },
  },
  data() {
    const props = this.$props
    let formInline = {}
    props.searchList.forEach((item) => {
      formInline[item.model] = undefined
    })
    return {
      formInline,
      searchItems,
      searchParams: { ...formInline },
      loading: false,
    }
  },
  render() {
    return (
      <Form inline={true} props={{ model: this.formInline }}>
        <Row type="flex" justify="space-between">
          <div
            style={{
              flex: '1 1 0%',
            }}
          >
            {this.renderSearchList()}
          </div>
          <div span={false}>{this.renderExtra(this.$slots.extra)}</div>
        </Row>
      </Form>
    )
  },
  install: function (Vue) {
    Vue.component(this.name, this)
  },
})
